package com.hzlh.common.coupon;

import com.alibaba.fastjson.JSON;
import com.hzlh.common.http.HttpService;
import com.hzlh.exception.GlobalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: CKQ
 * @DateTime: 2020/8/18 9:27
 * @Description: TODO
 */
@Slf4j
@Service
public class CouponRequest {

    public static String COUPON_LOGIN = "coupon_login:customer_";

    @Value("${system.couponAppId}")
    private String couponAppId;
    @Value("${system.couponUrl}")
    private String couponUrl;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private HttpService httpService;

    /**
     * @Description：通用的接口请求
     * @DateTime：2020/8/18 9:36
     * @Params：active 方法
     * @Return：
     */
    public Object doRequest(String key, Map<String, Object> params, CouponCustomerInfo couponCustomerInfo) {
        try {
            couponCustomerInfo.setAppId(couponAppId);
            InterfaceInfo interfaceInfo = ActiveConfig.getInterfaceInfo(key);
            if (interfaceInfo == null) {
                throw GlobalException.build("请求方法不能为空");
            }

            String authToken = this.getCouponAuthToken(couponCustomerInfo);
            if (StringUtils.isEmpty(authToken)) {
                throw GlobalException.build("卡券身份令牌获取失败");
            }
            Map<String, String> headerMap = this.initHeader(authToken);
            String result = "";
            switch (interfaceInfo.getMode()) {
                case "get":
                        result = httpService.doGet(couponUrl + interfaceInfo.getMethod(), params, headerMap);
                    break;
                case "post":
                        result = httpService.doPost(couponUrl + interfaceInfo.getMethod(), JSON.toJSONString(params), headerMap);
                    break;
                case "delete":
                        result = httpService.doDelete(couponUrl + interfaceInfo.getMethod(), params, headerMap);
                    break;
                case "put":
                        result = httpService.doPut(couponUrl + interfaceInfo.getMethod(), JSON.toJSONString(params), headerMap);
                    break;
                default:
                    break;
            }
            if (StringUtils.isEmpty(result)) {
                LOGGER.error("请求中台优惠券系统失败---请求地址：" + JSON.toJSONString(interfaceInfo) + "请求参数:" + JSON.toJSONString(params));
                throw GlobalException.build("请求失败，请重试！");
            }
            Map resultMap = (Map) JSON.parse(result);
            if (resultMap != null) {
                if (resultMap.get("code").toString().equals("200")) {
                    if (resultMap.containsKey("data")) {
                        return resultMap.get("data");
                    } else {
                        return new HashMap<>();
                    }
                }else if(resultMap.get("code").toString().equals("10022")){
                    stringRedisTemplate.delete(COUPON_LOGIN + couponCustomerInfo.getCustomerId());
                    throw GlobalException.build(resultMap.get("请求失败，请重试！").toString());
                }
                else {
                    throw GlobalException.build(resultMap.get("msg").toString());
                }
            }
            return new HashMap();
        } catch (Exception ex) {
            LOGGER.error("公用优惠券请求接口错误：" + ex.getMessage());
            if( !StringUtils.isEmpty(((GlobalException) ex).getResponseCode().getMsg())){
                throw GlobalException.build(((GlobalException) ex).getResponseCode().getMsg());
            }else {
                throw GlobalException.build("请求失败，请重试");
            }
        }
    }



    /**
     * @Description：登录表单系统并返回跳转地址
     * @DateTime：2020/8/6 17:49
     * @Params：
     * @Return：
     */
    private String getCouponAuthToken(CouponCustomerInfo couponCustomerInfo) {
        String authToken = stringRedisTemplate.opsForValue().get(COUPON_LOGIN + couponCustomerInfo.getCustomerId());
        if (!StringUtils.isEmpty(authToken)) {
            return authToken;
        }
        try {
            couponCustomerInfo.setAppId(couponAppId);
            Map<String, String> headerMap = this.initHeader("");
            String result = httpService.doPost(couponUrl + "/login/getAuthToken", JSON.toJSONString(couponCustomerInfo), headerMap);
            Map resultMap = (Map) JSON.parse(result);
            if (resultMap != null) {
                if (resultMap.get("code").toString().equals("200") && resultMap.get("data") != null) {
                    Map dataMap = (Map) JSON.parse(resultMap.get("data").toString());
                    stringRedisTemplate.opsForValue().set(COUPON_LOGIN + couponCustomerInfo.getCustomerId(), dataMap.get("authToken").toString(), 30, TimeUnit.MINUTES);
                    return dataMap.get("authToken").toString();
                } else {
                    throw GlobalException.build(resultMap.get("msg").toString());
                }
            }
        } catch (Exception ex) {
            LOGGER.error("getCouponAuthToken----获取优惠券登录认证失败", ex);
            throw GlobalException.build("认证失败");
        }
        throw GlobalException.build("认证失败");
    }

    /**
     * @Description：生成header
     * @DateTime：2020/8/18 9:43
     * @Params：customerId 用户ID 传则需要组装authToken，不传则不用组装
     * @Return：
     */
    private Map<String, String> initHeader(String authToken) {
        Map<String, String> headerMap = new HashMap<>();
        if (StringUtils.isEmpty(authToken)) {
            headerMap.put("appId", couponAppId);
        } else {
            headerMap.put("authToken", authToken);
        }
        headerMap.put("Content-Type", "application/json");
        return headerMap;
    }
}
